import 'package:flutter/material.dart';
import 'package:flutter_massage/common_lib/extension/ex_widget.dart';
import 'package:flutter_massage/common_lib/index.dart';
import 'package:flutter_massage/common_lib/routers/route.dart';
import 'package:flutter_massage/common_lib/ui/common_component.dart';
import 'package:flutter_massage/generated/assets.dart';
import 'package:flutter_massage/pages/login/index.dart';
import 'package:flutter_massage/pages/my/address/address_bean.dart';
import 'package:flutter_massage/pages/technician/choose_address/choose_address_page.dart';
import 'package:flutter_massage/pages/technician/place_order/place_order_logic.dart';
import 'package:flutter_massage/service/index.dart';
import 'package:flutter_massage/values/colors.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:intl/intl.dart';

class PlaceOrderPage extends GetView<PlaceOrderLogic> {
  const PlaceOrderPage({super.key, required this.projectId, required this.technicianId});

  final int projectId;
  final int technicianId;

  @override
  Widget build(BuildContext context) {
    return BaseScaffold(
      titleStr: '预约下单',
      scaffoldBackgroundColor: AppColors.grayF8,
      resizeToAvoidBottomInset: false,
      child: GetBuilder<PlaceOrderLogic>(
        init: PlaceOrderLogic(projectId: projectId, technicianId: technicianId),
        assignId: true,
        builder: (logic) {
          return Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              SingleChildScrollView(
                child: Column(
                  children: [
                    PlaceOrderAddress(logic).padding(horizontal: 12.w, top: 12.w),
                    PlaceOrderInfo(logic).padding(horizontal: 12.w, top: 12.w),
                    PlaceOrderNotes(logic).padding(horizontal: 12.w, top: 12.w),
                  ],
                ),
              ).expanded(),
              Container(
                height: 50.w + ScreenUtil().bottomBarHeight,
                alignment: Alignment.center,
                padding: EdgeInsets.only(bottom: ScreenUtil().bottomBarHeight),
                decoration: CommonDecoration.getBorder(
                  top: BorderSide(color: '#D7D7D7'.toColor, width: 0.5.w),
                  bg: Colors.white,
                ),
                child: logic.projectBean != null
                    ? Row(
                        children: [
                          const TextWidget.oneLine(
                            text: '订单金额：',
                            fontSize: 12,
                            color: AppColors.textLevelOne,
                          ),
                          Text.rich(
                            TextSpan(
                              text: '¥',
                              children: [
                                TextSpan(
                                  text: logic.projectBean!.itemPrice ?? '',
                                  style: const TextStyle(
                                    fontSize: 21,
                                    color: AppColors.primaryOrange,
                                    fontWeight: FontWeight.bold,
                                  ),
                                ),
                              ],
                              style: const TextStyle(
                                fontSize: 12,
                                color: AppColors.primaryOrange,
                                fontWeight: FontWeight.bold,
                              ),
                            ),
                          ).expanded(),
                          ButtonWidget.text(
                            '立即下单',
                            textColor: Colors.white,
                            alignment: Alignment.center,
                            width: 115.w,
                            height: 40.w,
                            borderRadius: 40.w,
                            gradient: CommonDecoration.xydGradient,
                            fontSize: 15,
                            fontWeight: FontWeight.bold,
                            hasInkWell: false,
                            onTap: () async {
                              if (XydUserService.key.empty) {
                                CommonRoute.open(const LoginPage());
                                return;
                              }
                              logic.save();
                              return;
                              ActionBottomSheet.popModal(
                                safeBottom: false,
                                safeAreaMinimum: EdgeInsets.fromLTRB(16.w, 0, 16.w, 28.w),
                                child: Container(
                                  decoration: CommonDecoration.getShapeDecoration(radius: 16.w, bg: AppColors.white),
                                  child: Column(
                                    mainAxisSize: MainAxisSize.min,
                                    crossAxisAlignment: CrossAxisAlignment.start,
                                    children: [
                                      ButtonWidget.icon(
                                        Assets.svgDialogClose.toSvg(width: 8.w),
                                        hasInkWell: false,
                                        padding: EdgeInsets.all(16.w),
                                        onTap: () => CommonRoute.close(),
                                      ).alignRight(),
                                      Row(
                                        mainAxisAlignment: MainAxisAlignment.center,
                                        children: [
                                          _buildBtn('支付宝', Assets.svgPayAli, () {}),
                                          CommonMargin.width(73.w),
                                          _buildBtn('微信', Assets.svgPayWechat, () {}),
                                        ],
                                      ).padding(top: 6.w, bottom: 28.w),
                                    ],
                                  ),
                                ),
                              );
                            },
                          ),
                        ],
                      ).paddingHorizontal(16.w)
                    : null,
              ),
            ],
          );
        },
      ),
    );
  }

  Widget _buildBtn(String title, String icon, VoidCallback onTap) {
    return ButtonWidget(
      hasInkWell: false,
      onTap: () {
        CommonRoute.close();
        onTap.call();
      },
      child: Column(
        children: [
          icon.toSvg(width: 70.w),
          TextWidget.oneLine(text: title, fontSize: 14, color: AppColors.textLevelThree).paddingTop(6.w),
        ],
      ),
    );
  }
}

class PlaceOrderAddress extends StatelessWidget {
  const PlaceOrderAddress(this.logic, {super.key});

  final PlaceOrderLogic logic;

  @override
  Widget build(BuildContext context) {
    return ButtonWidget(
      height: 90.w,
      onTap: () => CommonRoute.open(
        ChooseAddressPage(
          onChoose: (AddressBean bean) {
            logic.addressBean = bean;
            logic.update();
          },
        ),
      ),
      hasInkWell: false,
      child: Row(
        children: [
          (logic.addressBean == null ? empty() : notEmpty()).expanded(),
          Assets.svgArrowRightGray.toSvg(width: 8.w),
        ],
      ),
    ).card(radius: 8.w, padding: EdgeInsets.symmetric(horizontal: 12.w));
  }

  Widget empty() => const TextWidget.oneLine(
        text: '请选择您的地址',
        fontSize: 18,
        color: AppColors.textLevelOne,
        fontWeight: FontWeight.bold,
      );

  Widget notEmpty() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        TextWidget.moreLine(
          text: logic.addressBean!.address ?? '',
          fontSize: 18,
          color: AppColors.textLevelOne,
          fontWeight: FontWeight.bold,
          maxLines: 2,
          overflow: TextOverflow.ellipsis,
        ),
        Row(
          children: [
            TextWidget.oneLine(
              text: logic.addressBean!.name ?? '',
              fontSize: 12,
              color: AppColors.textLevelThree,
            ).flexible(),
            TextWidget.oneLine(
              text: logic.addressBean!.phone.encryptPhone,
              fontSize: 12,
              color: AppColors.textLevelThree,
            ).paddingLeft(32.w),
          ],
        ).paddingTop(10.w),
      ],
    );
  }
}

class PlaceOrderInfo extends StatelessWidget {
  const PlaceOrderInfo(this.logic, {super.key});

  final PlaceOrderLogic logic;

  @override
  Widget build(BuildContext context) {
    if (logic.projectBean == null) return Container();
    return Row(
      children: [
        ImageWidget.url(
          logic.projectBean!.itemImage ?? '',
          width: 80.w,
          height: 80.w,
          radius: 6.w,
        ),
        CommonMargin.width(8.w),
        Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            TextWidget.moreLine(
              text: logic.projectBean!.itemName ?? '',
              fontSize: 15,
              color: AppColors.textLevelOne,
              fontWeight: FontWeight.bold,
              maxLines: 2,
              overflow: TextOverflow.ellipsis,
            ),
            const TextWidget.oneLine(
              text: 'x1',
              fontSize: 11,
              color: AppColors.textLevelOne,
              fontWeight: FontWeight.bold,
            ).paddingTop(6.w),
            const Spacer(),
            Text.rich(
              TextSpan(
                text: '¥',
                children: [
                  TextSpan(
                    text: logic.projectBean!.itemPrice ?? '',
                    style: const TextStyle(
                      fontSize: 17,
                      color: AppColors.primaryOrange,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                ],
                style: const TextStyle(
                  fontSize: 12,
                  color: AppColors.primaryOrange,
                  fontWeight: FontWeight.bold,
                ),
              ),
            ),
          ],
        ).height(80.w).expanded(),
      ],
    ).card(radius: 8.w, padding: EdgeInsets.all(16.w));
  }
}

class PlaceOrderNotes extends StatelessWidget {
  const PlaceOrderNotes(this.logic, {super.key});

  final PlaceOrderLogic logic;

  @override
  Widget build(BuildContext context) {
    if (logic.technicianBean == null) return Container();
    return Column(
      children: [
        _buildItem('服务技师', logic.technicianBean!.name ?? ''),
        _buildItem(
          '服务时间',
          logic.time.getAuto('请选择服务时间'),
          onTap: () {
            ActionBottomSheet.showDatePicker(
              title: '请选择年龄',
              onConfirm: (DateTime? dateTime, String year, String month, String day, String hour, String minute) {
                if (dateTime != null) {
                  logic.time = DateFormat('yyyy-MM-dd hh:mm').format(dateTime);
                  logic.update();
                }
              },
            );
          },
        ),
        ClipRRect(
          borderRadius: BorderRadius.all(Radius.circular(8.w)),
          child: TextField(
            decoration: const InputDecoration(
              border: InputBorder.none,
              hintText: '如有特殊情况请提前告知（选填）',
              hintStyle: TextStyle(fontSize: 13, color: AppColors.textLevelThree),
              fillColor: AppColors.grayF8,
              filled: true,
            ),
            cursorColor: AppColors.primaryGreen,
            controller: logic.textEditingController,
            focusNode: logic.focusNode,
            style: const TextStyle(fontSize: 16),
            maxLines: 4,
          ),
        ).paddingTop(6.w),
      ],
    ).card(radius: 8.w, padding: EdgeInsets.all(12.w));
  }

  Widget _buildItem(String title, String content, {VoidCallback? onTap}) {
    return Row(
      children: [
        TextWidget.oneLine(
          text: title,
          fontSize: 12,
          color: AppColors.textLevelOne,
        ),
        ButtonWidget.text(
          content,
          fontSize: 12,
          fontWeight: FontWeight.bold,
          textColor: AppColors.textLevelOne,
          hasInkWell: false,
          onTap: onTap,
        ).alignRight().expanded(),
        if (onTap != null) Assets.svgArrowRightGray.toSvg(width: 8.w).paddingLeft(4.w),
      ],
    ).paddingVertical(6.w);
  }
}
